package com.example.oms.common.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import com.example.oms.common.config.PageParam;
import com.example.oms.common.config.SortingField;
import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;

public class MyBatisUtils {
    private static final String MYSQL_ESCAPE_CHARACTER = "`";

    public MyBatisUtils() {
    }

    public static <T> Page<T> buildPage(PageParam pageParam) {
        return buildPage(pageParam, (Collection)null);
    }

    public static <T> Page<T> buildPage(PageParam pageParam, Collection<SortingField> sortingFields) {
        Page<T> page = new Page((long)pageParam.getPageNo(), (long)pageParam.getPageSize());
        if (!CollectionUtil.isEmpty(sortingFields)) {
            page.addOrder((List)sortingFields.stream().map((sortingField) -> {
                return "asc".equals(sortingField.getOrder()) ? OrderItem.asc(sortingField.getField()) : OrderItem.desc(sortingField.getField());
            }).collect(Collectors.toList()));
        }

        return page;
    }

    public static void addInterceptor(MybatisPlusInterceptor interceptor, InnerInterceptor inner, int index) {
        List<InnerInterceptor> inners = new ArrayList(interceptor.getInterceptors());
        inners.add(index, inner);
        interceptor.setInterceptors(inners);
    }

    public static String getTableName(Table table) {
        String tableName = table.getName();
        if (tableName.startsWith("`") && tableName.endsWith("`")) {
            tableName = tableName.substring(1, tableName.length() - 1);
        }

        return tableName;
    }

    public static Column buildColumn(String tableName, Alias tableAlias, String column) {
        if (tableAlias != null) {
            tableName = tableAlias.getName();
        }

        return new Column(tableName + "." + column);
    }
}